import requests  # 导入requests库，用于发送HTTP请求
import random  # 导入random库，用于生成随机噪音
import string  # 导入string库，用于处理字符串操作


def string_to_base256_number(s):
    """ 将字符串转换为基于256的数字 """
    num = 0
    for char in s:
        num = num * 256 + ord(char)  # 每个字符转换为ASCII码并累加
    return num


def rsa_encrypt(message, e, n):
    """ 使用RSA加密 """
    return pow(message, e, n)  # 使用Python内置函数pow进行快速模幂运算


def rsa_decrypt(ciphertext, d, n):
    """ 使用RSA解密 """
    return pow(ciphertext, d, n)  # 使用Python内置函数pow进行快速模幂运算


def add_noise_to_password(password):
    """ 给密码添加噪音 """
    noise_length = 16  # 定义噪音长度
    noise = ''.join(random.choices(string.ascii_letters + string.digits, k=noise_length))  # 生成随机噪音字符串
    noisy_password = password + '\0' + noise  # 将密码和噪音以'\0'分隔连接起来
    return noisy_password


def encrypt_string_and_convert_to_hex(s, e, n):
    """ 加密字符串并转换为十六进制 """
    base256_number = string_to_base256_number(s)  # 将字符串转换为基于256的数字
    encrypted_number = rsa_encrypt(base256_number, e, n)  # 使用RSA加密数字
    hex_encrypted = hex(encrypted_number)[2:]  # 将加密后的数字转换为十六进制字符串，并去除前缀'0x'
    return hex_encrypted


# 给定的公钥
e = 65537
n = 135261828916791946705313569652794581721330948863485438876915508683244111694485850733278569559191167660149469895899348939039437830613284874764820878002628686548956779897196112828969255650312573935871059275664474562666268163936821302832645284397530568872432109324825205567091066297960733513602409443790146687029

# 示例用户名和密码
username = "0211423595"
password = "ys100820"

# 添加噪音到密码
noisy_password = add_noise_to_password(password)
print(f"Noisy password: {noisy_password}")  # 打印带噪音的密码

# 加密带噪音的密码并转换为16进制
hex_encrypted_password = encrypt_string_and_convert_to_hex(noisy_password, e, n)
print(f"Hex encrypted password: {hex_encrypted_password}")  # 打印加密后的十六进制密码

# 提交的URL
url = "http://183.175.12.27:8002/step_05"

# 构造参数
param = {
    "user": username,
    "password": hex_encrypted_password
}

# 提交请求并获取响应
response = requests.get(url, params=param)
response_data = response.json()  # 解析响应的JSON数据

print(response_data)  # 打印响应数据

if response_data["is_success"]:
    encrypted_message = response_data["message"]  # 获取加密消息
    encrypted_message_number = int(encrypted_message, 16)  # 将十六进制消息转换为整数

    # 使用公钥解密消息
    decrypted_message_number = rsa_encrypt(encrypted_message_number, e, n)
    # 将解密后的数字转换为字节并解码为字符串，忽略错误
    decrypted_message = decrypted_message_number.to_bytes((decrypted_message_number.bit_length() + 7) // 8,
                                                          'big').decode('utf-8', errors='ignore')

    # 查找\0字符并截取其前面的部分
    decrypted_message = decrypted_message.split('\0')[0]
    print(f"Decrypted message: {decrypted_message}")  # 打印解密后的消息
else:
    print("Request failed.")  # 如果请求失败，则打印失败消息
